import json
import socket
import threading


class Udp:
    def __init__(self, destination_ip, destination_port, local_ip=None, local_port=8110, auto_receive=False):
        self._udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        bind_ip = local_ip if local_ip else ''
        self._udp.bind((bind_ip, int(local_port)))
        self._destination_ip = destination_ip
        self._destination_port = destination_port
        self._thread = None
        if auto_receive:
            self._thread = threading.Thread(target=self._rcv_worker).start()

    def close(self):
        self._udp.close()

    def send(self, data, encode='utf8'):
        if isinstance(data, dict):
            send_data = json.dumps(data).encode(encode)
        elif isinstance(data, str):
            send_data = data.encode('utf8')
        elif isinstance(data, bytes) or isinstance(data, bytearray):
            send_data = data
        else:
            raise Exception('数据类型：[%s]无效' % type(data))
        self._udp.sendto(send_data, (self._destination_ip, int(self._destination_port)))

    def _rcv_worker(self, buf_size=10240):
        data = self._udp.recvfrom(buf_size)
        self.auto_recv(data)

    def auto_recv(self, data):
        pass

    def recv(self, buf_size=10240):
        return self._udp.recvfrom(buf_size)
